#!/usr/bin/python

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or (at
#  your option) any later version.
#
#  This program is distributed in the hope that it will be useful, but
#  WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program; if not, write to the Free Software Foundation, Inc.,
#  59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
import sys
import math
from qt import *
from visacontrol import *
from devicesconfig import *
import time

#
# in controlpart.py there are all classes to control a measurement
# 
# Classes: 	gpibsComboBox:	holds a list of all know gpib-numbers (found through the visa driver)
#		axesComboBox:	combobox to choose the axes to plot to
#		modesComboBox:	combobox to choose the mode in which you want to measure a instrument
#		geraeteComboBox:combobox which holds all know instruments from devicesconfig
#		gpibDevice:	Combines the above classes to control ONE instrument
#		writeReadConf:	holds (unlimited) gpibDevice-classes to control n instruments
#		mainWriteReadConf:	combines 2 writeReadConf-Classes, one for the batchmode and one for the measurement
#


class gpibsComboBox(QComboBox):
	def __init__(self,parent,virtualNumber):
        	QWidget.__init__(self,parent)
		#self.label.setFixedWidth( self.label.sizeHint().width() )
		self.clear()
		gpibs=get_visa_instruments_list()
		self.insertItem("(none)")
		self.insertItem("virtual"+str(virtualNumber))
		for i in gpibs:
			self.insertItem(i)
		self.setEditable(True)
		self.setFixedWidth( self.sizeHint().width() )
		#self.label.setText("title")
		QToolTip.add( self, "Select VISA-address (of the device choosen left)")
		
	def getAddress(self):
		return self.currentText()
		
class axesComboBox(QComboBox):
	def __init__(self,parent):
        	QWidget.__init__(self,parent)
		#self.label.setFixedWidth( self.label.sizeHint().width() )
		self.clear()
		self.insertItem('-') #0
		self.insertItem('x') #1
		self.insertItem('y') #2
		self.insertItem('x,y') #3
		self.insertItem('y,x') #4
		self.insertItem('-,x') #5
		self.insertItem('-,y') #6
		self.insertItem('y2') #7
		self.insertItem('-,y2') #8
		#self.insertItem('x2')
		#self.insertItem('y2')		
		#self.insertItem('x2,y2')
		#self.insertItem('y2,x2')
		#self.insertItem('-,x2')
		#self.insertItem('-,y2')		
		self.setEditable(False)
		self.setFixedWidth( self.sizeHint().width() )
		
class modesComboBox(QComboBox):
	def __init__(self,parent):
        	QWidget.__init__(self,parent)
		#self.label.setFixedWidth( self.label.sizeHint().width() )
		self.clear()
		self.insertItem(' ')
		self.insertItem('|...')
		self.insertItem('-->')
		self.setEditable(False)
		self.setFixedWidth( self.sizeHint().width() )
		self.connect(self,SIGNAL("activated(int)"),self.newActivated)
		self.newActivated(0)
		
	def newActivated(self,n):
		if n==0:	  QToolTip.add( self, "measuremode undefined" )
		elif n==1: QToolTip.add( self, "fix device on left value" )
		elif n==2: QToolTip.add( self, "change value from left value to right value in n steps" )
		
class geraeteComboBox(QComboBox):
	def __init__(self,parent):
        	QComboBox.__init__(self,parent)
		#self.label.setFixedWidth( self.label.sizeHint().width() )
		self.clear()
		self.devices=allDevices() #Geraetepart
		self.device=[]
		
		for x in self.devices.all():
			eval('self.device.append('+x+'())')
			self.insertItem(self.device[len(self.device)-1].name)

		self.setEditable(False)
		self.setFixedWidth( self.sizeHint().width() )
		self.connect(self,SIGNAL("activated(int)"),self.newActivated)
		self.current=0
		
	def getDeviceName(self):
		x=self.devices.all()
		return x[self.currentItem()]
		
	def newActivated(self,n):
		self.current=n
		#print n,self.device[n].typ
		tooltip="Device output form: "+str(self.device[n].resultform)
		QToolTip.add( self, str(self.device[n].description) )
 		self.emit(PYSIGNAL("deviceChanged"), (self.device[n].typ,tooltip))

		
		
class gpibDevice(QWidget):
	def __init__(self,parent,title,virtualNumber):
		QWidget.__init__(self,parent)
		self.label1 = QLabel(title,self)
		self.label1.setFixedWidth( self.label1.sizeHint().width() )
		self.label2 = QLabel('Steps:',self)
		self.label2.setFixedWidth( self.label2.sizeHint().width() )		
		self.axes = axesComboBox(self)
		self.mode = modesComboBox(self)
		self.gpib = gpibsComboBox(self,virtualNumber)
		self.beginn = QComboBox(self)
		self.beginn.setEditable(True)
		self.beginn.insertItem('1')
		self.beginn.insertItem('2')
		self.beginn.insertItem('5')
		self.beginn.insertItem('10')
		self.beginn.insertItem('100')
		self.beginn.insertItem('500')
		self.beginn.insertItem('1000')
		self.beginn.setCurrentItem(0)
		
		self.ende = QComboBox(self)
		self.ende.setEditable(True)
		self.ende.insertItem('1')
		self.ende.insertItem('2')
		self.ende.insertItem('5')
		self.ende.insertItem('10')
		self.ende.insertItem('100')
		self.ende.insertItem('500')
		self.ende.insertItem('1000')
		self.ende.setCurrentItem(3)		
		
		self.steps = QComboBox(self)
		self.steps.setEditable(True)
		self.steps.insertItem('1')
		self.steps.insertItem('3')
		self.steps.insertItem('5')
		self.steps.insertItem('10')
		self.steps.insertItem('21')
		self.steps.insertItem('101')
		self.steps.insertItem('201')
		self.steps.insertItem('401')
		self.steps.insertItem('1001')
		self.steps.setCurrentItem(4)
		self.geraete = geraeteComboBox(self)
		
		#self.beginn.setCurrentText("1")
		#self.ende.setCurrentText("10")
		self.steps.setCurrentItem(3)
		#self.axes.setCurrentItem(5)
		self.mode.setCurrentItem(2)
		
		
		l = QGridLayout(self,1,10)
		l.setSpacing(5)
		#l.setMargin(10)
	        l.addWidget(self.label1,0,0)
		l.addWidget(self.geraete,0,1)
		l.addWidget(self.gpib,0,2)
		l.addWidget(self.axes,0,3)
		l.addWidget(self.beginn,0,4)
		l.addWidget(self.mode,0,5)
		l.addWidget(self.ende,0,6)
		l.addWidget(self.label2,0,7)
		l.addWidget(self.steps,0,8)
		self.connect(self.geraete,PYSIGNAL("deviceChanged"),self.deviceChanged)
		self.geraete.newActivated(0)
		
		QToolTip.add( self.beginn, "Start value (or fixed value) for this device")
		QToolTip.add( self.ende, "End value for the device (only relevant if --> choosen)")
		QToolTip.add( self.steps, "Number of steps to go from the start to the end value (only relevant if --> choosen)")

		
	#def getStep(self,value):
	#	print "ERROR: getStep von Geraeteklasse nicht ueberschrieben!"
	#	return self.step
	
	def deviceChanged(self,typ,tooltip="Output form: unknown"):
		if (typ=="r")or(typ=="vr"):
			self.beginn.setEnabled(False)
			self.ende.setEnabled(False)
			self.steps.setEnabled(False)
			self.mode.setCurrentItem(0)
			self.mode.setEnabled(False)
			self.gpib.setEnabled(True)
			self.axes.setEnabled(True)
		elif (typ=="w")or(typ=="vw"):
			self.beginn.setEnabled(True)
			self.ende.setEnabled(True)
			self.steps.setEnabled(True)
			self.mode.setEnabled(True)
			self.gpib.setEnabled(True)
			self.axes.setEnabled(True)
		elif (typ=="rw")or(typ=="vrw"):
			self.beginn.setEnabled(True)
			self.ende.setEnabled(True)
			self.steps.setEnabled(True)
			self.mode.setEnabled(True)
			self.gpib.setEnabled(True)
			self.axes.setEnabled(True)
		elif (typ=="srw")or(typ=="vsrw"):
			self.beginn.setEnabled(True)
			self.ende.setEnabled(False)
			self.steps.setEnabled(False)
			self.mode.setCurrentItem(2)
			self.mode.setEnabled(False)
			self.gpib.setEnabled(True)
			self.axes.setEnabled(True)
		elif typ=="none":
			self.beginn.setEnabled(False)
			self.ende.setEnabled(False)
			self.steps.setEnabled(False)
			self.mode.setCurrentItem(0)
			self.mode.setEnabled(False)
			self.gpib.setEnabled(False)
			self.axes.setEnabled(False)
		else:
			print "ERROR: GPIB-Devicetyp unknown:",typ
			self.gpib.setCurrentItem(1)
			
		if typ.find("v")>-1:
			self.gpib.setCurrentItem(1)		
			self.gpib.setEnabled(False)
			
		QToolTip.add( self.axes, "Plot data on axes/axis ("+str(tooltip)+")" );
		
	
		

class writeReadConf(QWidget):
	def __init__(self,parent,visa,batchmode=False):
		QWidget.__init__(self,parent)
		self.batchmode=batchmode
		self.virtualNumber=0
		self.label = QLabel('Setup your devices, if you need/have more, click here:',self)
		self.morebutton = QPushButton ("click (more devices)",self)
		QToolTip.add( self.morebutton, "Adds a new device-line, so that you can control one more instrument.")
		#self.startbutton = QPushButton ("Messen",self)
		self.connect(self.morebutton,SIGNAL('clicked()'),self.moreclicked)
		#self.connect(self.startbutton,SIGNAL('clicked()'),self.startclicked)
		self.device=[]
		
		number=str(self.virtualNumber)
		self.virtualNumber+=1
		if self.batchmode: number="batch"+number
		self.device.append(gpibDevice(self,' ',number))
		#self.device.append(gpibDevice(self,' ',))
		
		self.l = QGridLayout(self,2,5)
		self.l.setSpacing(5)
		self.l.addWidget(self.label,0,0)
		self.l.addWidget(self.morebutton,0,1)
		#self.l.addWidget(self.startbutton,1,1)
		self.l.addMultiCellWidget(self.device[0],1,1,0,1) 
		#self.l.addMultiCellWidget(self.device[1],2,2,0,1) 
	        self.visa=visa
		self.timer = QTimer(self)
		self.count=1
    		self.connect( self.timer, SIGNAL('timeout()'), self.timerEvent)	
		self.stop=False

	
	def moreclicked(self):
		#print "x",self.c
		number=str(self.virtualNumber)
		self.virtualNumber+=1
		if self.batchmode: number="batch"+number		
		self.device.append(gpibDevice(self,' ',number))
		n=len(self.device)
		self.l.addMultiCellWidget(self.device[n-1],n+1,n+1,0,1) #,self.c,0)
		self.device[n-1].show()


	def timerEvent(self):
		#print "TimerEvent",self.count
		self.visa.readAll(self.count)
		#print "timerEvent: keine Messdaten"
		#self.emit(PYSIGNAL('endMessung'),())


	def start(self,count=1):
		print "Start Measurement..."
		self.count=count
		for x in self.device:
			n=x.geraete.currentItem()
			if x.geraete.device[n].typ!="none":
				self.visa.doInit(x.geraete.getDeviceName(),x.gpib.getAddress(),x.geraete.device[n].typ,float(str(x.beginn.currentText())),int(x.mode.currentItem()),float(str(x.ende.currentText())),float(str(x.steps.currentText())))
				#if len(str(x.beginn.currentText()))>0:
				self.visa.setStepPos(x.geraete.getDeviceName(),x.gpib.getAddress(),float(str(x.beginn.currentText())))
				currPos=self.visa.getStepPos(x.geraete.getDeviceName(),x.gpib.getAddress())
				self.visa.doStep(x.geraete.getDeviceName(),x.gpib.getAddress(),currPos)
				
		if self.batchmode==False:
			self.timer.start(100,True)
		
	def nextMesspunkt(self):
		isNext=False #Noch ein Messpunkt?
		if self.stop==True: return False
		for x in self.device:
			n=x.geraete.currentItem()
			if x.geraete.device[n].typ!="none":
				if x.mode.currentItem()==2: # -->
					fbegin = float(str(x.beginn.currentText()))
					fend   = float(str(x.ende.currentText()))
					if (float(str(x.steps.currentText())))>1:
                                            stepsize=abs(fbegin-fend)/(float(str(x.steps.currentText()))-1)
                                        else:
                                            stepsize=abs(fbegin-fend)
					if fbegin>fend: #Abwaerts zaehlen
						stepsize=(-1)*stepsize
					self.visa.incStepPos(x.geraete.getDeviceName(),x.gpib.getAddress(),stepsize)
					currPos=self.visa.getStepPos(x.geraete.getDeviceName(),x.gpib.getAddress())
					#print "Set to ",currPos
					if fbegin<fend:
						if fend>0: fend=fend*1.0001
						if fend<0: fend=fend*0.9999
						if currPos<=fend:
							isNext=True
							self.visa.doStep(x.geraete.getDeviceName(),x.gpib.getAddress(),currPos)
					else:
						if fend<0: fend=fend*1.0001
						if fend>0: fend=fend*0.9999						
						if currPos>=fend:
							isNext=True
							self.visa.doStep(x.geraete.getDeviceName(),x.gpib.getAddress(),currPos)						
									
		if self.batchmode==False:
			if isNext==True:
				self.timer.start(100,True)
			else:
				self.emit(PYSIGNAL('endMessung'),())
				#print "Ender der Messung (kein neuer Read/Data-Befehl)"
				
		return isNext
		

				
class mainWriteReadConf(QWidget):
	def __init__(self,parent):
		QWidget.__init__(self,parent)
		self.visa=visaControl(self)
		
		selfLayout = QGridLayout(self,1,1,11,6,"mainWriteReadConf")

                self.groupBox2 = QGroupBox(self,"groupBox1")
		self.groupBox2.setTitle("Measurement configuration for the Batchmode...")
        	self.groupBox2.setColumnLayout(0,Qt.Vertical)
        	self.groupBox2.layout().setSpacing(6)
        	self.groupBox2.layout().setMargin(11)
        	groupBox2Layout = QGridLayout(self.groupBox2.layout())
        	groupBox2Layout.setAlignment(Qt.AlignTop)

        	self.batchwritereadconf = writeReadConf(self.groupBox2,self.visa,True)
        	groupBox2Layout.addMultiCellWidget(self.batchwritereadconf,1,1,0,5)

                self.groupBox = QGroupBox(self.groupBox2,"groupBox1")
		self.groupBox.setTitle("Measurement...")
        	self.groupBox.setColumnLayout(0,Qt.Vertical)
        	self.layout().setSpacing(3) #6)
        	self.layout().setMargin(8)
        	groupBoxLayout = QGridLayout(self.groupBox.layout())
        	groupBoxLayout.setAlignment(Qt.AlignTop)

        	self.writereadconf = writeReadConf(self.groupBox,self.visa)
        	groupBoxLayout.addWidget(self.writereadconf,0,0)
        	groupBox2Layout.addMultiCellWidget(self.groupBox,2,2,0,5)
		
		self.commentLabel = QLabel("Comment this measurement:",self.groupBox2)
		self.comment = QLineEdit(self.groupBox2)
		QToolTip.add( self.comment, "This comment is added to the head of the saved file")
		
		self.startbutton = QPushButton ("Start measurement",self.groupBox2)
		QToolTip.add( self.startbutton, "Start the measurement, when finished it will be automatically saved")
		self.stopbutton = QPushButton ("stop",self.groupBox2)
		QToolTip.add( self.stopbutton, "Stop the measurement, data will be saved")
		self.stopbutton.setEnabled(False)
		self.stopbutton.setFixedWidth( self.stopbutton.sizeHint().width() )
		self.countLabel = QLabel ("Average out of measuring points:",self.groupBox2)
		self.countLabel.setFixedWidth( self.countLabel.sizeHint().width() )
		self.countCombo = QComboBox(self.groupBox2)
		self.countCombo.setEditable(True)
		self.countCombo.insertItem("1")
		self.countCombo.insertItem("3")
		self.countCombo.insertItem("5")
		self.countCombo.insertItem("10")
		self.countCombo.insertItem("100")
		self.countCombo.setFixedWidth( self.countCombo.sizeHint().width() )
		self.countCombo.setCurrentItem(1)
		QToolTip.add( self.countCombo, "Do n readings and add the average as data (only on instruments where the property canAverage=True (see devicesconfig.py))")
		
		self.reverseCheckbox = QCheckBox ("Reverse range after measurement",self.groupBox2)
		self.reverseCheckbox.setFixedWidth( self.reverseCheckbox.sizeHint().width() )		
		self.reverseCheckbox.setChecked(True)
		QToolTip.add( self.reverseCheckbox, "Reverse the start and stop value after each measurement (if --> is selected)")
		
		self.waitLabel = QLabel ("Wait n milliseconds between readings:",self.groupBox2)
		self.waitLabel.setFixedWidth( self.waitLabel.sizeHint().width() )
		self.waitCombo = QComboBox(self.groupBox2)
		self.waitCombo.setEditable(True)
		self.waitCombo.insertItem("100")
		self.waitCombo.insertItem("200")
		self.waitCombo.insertItem("300")
		self.waitCombo.insertItem("1000")
		self.waitCombo.insertItem("10000")
		self.waitCombo.setFixedWidth( self.waitCombo.sizeHint().width() )
		self.waitCombo.setCurrentItem(1)
		QToolTip.add( self.waitCombo, "Wait (at least) n milliseconds between reading again/after setting of an instrument")
		
		self.repeatLabel = QLabel ("Repeat measurement n times:",self.groupBox2)
		self.repeatLabel.setFixedWidth( self.repeatLabel.sizeHint().width() )
		self.repeatCombo = QComboBox(self.groupBox2)
		self.repeatCombo.setEditable(True)
		self.repeatCombo.insertItem("1")
		self.repeatCombo.insertItem("2")
		self.repeatCombo.insertItem("4")
		self.repeatCombo.insertItem("10")
		self.repeatCombo.setFixedWidth( self.repeatCombo.sizeHint().width() )
		self.repeatCombo.setCurrentItem(0)
		QToolTip.add( self.repeatCombo, "Repeat measurement n times")
		
		
		groupBox2Layout.addWidget(self.commentLabel,3,0)
		groupBox2Layout.addMultiCellWidget(self.comment,3,3,1,5)
		groupBox2Layout.addWidget(self.countLabel,4,0,Qt.AlignLeft)
		groupBox2Layout.addWidget(self.countCombo,4,1,Qt.AlignLeft)
		groupBox2Layout.addWidget(self.repeatLabel,4,2)
		groupBox2Layout.addWidget(self.repeatCombo,4,3)
		groupBox2Layout.addWidget(self.startbutton,4,4)
		groupBox2Layout.addWidget(self.stopbutton,4,5)
		groupBox2Layout.addWidget(self.waitLabel,5,0)
		groupBox2Layout.addWidget(self.waitCombo,5,1)			
		groupBox2Layout.addMultiCellWidget(self.reverseCheckbox,5,5,2,3,Qt.AlignLeft)
	
		
		self.connect(self.startbutton,SIGNAL('clicked()'),self.start)
		self.connect(self.stopbutton,SIGNAL('clicked()'),self.stop)
				
        	selfLayout.addWidget(self.groupBox2,0,0)
		
		self.timer2 = QTimer(self)
    		self.connect( self.timer2, SIGNAL('timeout()'), self.timer2Event)
		
		self.connect(self.visa,PYSIGNAL('newMessdaten'),self.newMessdaten)
		self.connect(self.visa,PYSIGNAL('stopMessung'),self.stop)
		self.connect(self.visa,PYSIGNAL('endMessung'),self.endMessung) #Passiert nur wenn KEin Lesegeraet ausgewaehlt wurde
		self.connect(self.writereadconf,PYSIGNAL('endMessung'),self.endMessung)
		self.init=True
		
	
	def syntaxCheck(self):
		allRight=True
		for y in self.writereadconf.device,self.batchwritereadconf.device:
			for x in y:
				try:
					s=str(x.ende.currentText())
					if len(s)>0: i=float(s)
					s2=str(x.beginn.currentText())
					if len(s2)>0: i2=float(s2)
					s3=str(x.steps.currentText())
					if len(s3)>0: i3=float(s3)
				except:
					#print s,s2,s3,i,i2,i3
					allRight=False
				
				#if (str(x.ende.currentText())).isdigit()==False: error=True
				#if (str(x.beginn.currentText())).isdigit()==False: error=True
				#if (str(x.steps.currentText())).isdigit()==False: error=True

		if str(self.countCombo.currentText()).isdigit()==False: error=True
		if str(self.repeatCombo.currentText()).isdigit()==False: error=True
		return allRight
		
	def start(self):
		if self.syntaxCheck()==False:
			QMessageBox.critical( self, "pyvLab", "Invalid numbers found! Please correct them first.")
			return False
		
		self.stillToRepeat=int(str(self.repeatCombo.currentText()))
		self.startbutton.setEnabled(False)
		self.stopbutton.setEnabled(True)
		self.writereadconf.stop=False
		self.batchwritereadconf.stop=False
		self.visa.stop=False
		self.visa.resetInit(int(str(self.waitCombo.currentText()))) #Geraete werden neu initialisiert!
		self.batchwritereadconf.start()
		self.init=True
		self.timer2Event()
		self.init=False
		self.emit(PYSIGNAL('startMessung'),())
		
	def stop(self):
		self.startbutton.setEnabled(True)
		self.stopbutton.setEnabled(False)
		self.writereadconf.stop=True
		self.batchwritereadconf.stop=True
		self.visa.stop=True
		self.visa.thread.stop=True
		self.stillToRepeat=0
		if self.visa.thread.wait()==False:
			self.visa.thread.terminate()
			print "Warning Visa-Thread was terminated/killed! Restart pyvLab!"
			
		self.visa.resetInit() #Geraete werden neu initialisiert!
		self.emit(PYSIGNAL('endMessung'),())
		self.emit(PYSIGNAL('stopMessung'),())
		
	def reverseValues(self):
		for x in self.writereadconf.device:
			if (x.mode.currentItem()==2):
				begin=str(x.beginn.currentText())
				end=str(x.ende.currentText())
				self.setCombo(x.beginn,end)
				self.setCombo(x.ende,begin)
				
		
	def endMessung(self):
		self.emit(PYSIGNAL('endMessung'),())
		if self.reverseCheckbox.isChecked()==True: self.reverseValues()
		if self.stillToRepeat>1: #repeat measurement?
			self.stillToRepeat-=1
			print "Repeat Measurement"
			self.timer2.start( 3000, True )
		elif (self.batchwritereadconf.nextMesspunkt()==True):
			print "BatchNextEvent"
			self.stillToRepeat=int(str(self.repeatCombo.currentText()))
			self.timer2.start( 3000, True )
		else: 
			self.visa.finishAll()
			self.startbutton.setEnabled(True)
			self.stopbutton.setEnabled(False)
			self.emit(PYSIGNAL('endBatchMessung'), ())
			
	def timer2Event(self):
		print "BatchTimer2Event"
		head=self.getMessungsHead()
		self.emit(PYSIGNAL('newMessung'), (head,))
		
		self.plotLastXValue=0
		self.plotLastYValue=0
		self.plotYValue=0
		self.plotXValue=0
		self.plotIntegral=0
				
		self.writereadconf.start(int(str(self.countCombo.currentText()))) 
		
	def getMessungsHead(self):
		head=[]
		head.append("# "+time.strftime("%d %b %Y %H:%M:%S"))
		outputdata="x,y,y2"
		for x in self.batchwritereadconf.device:
			n=x.geraete.currentItem()
			if x.geraete.device[n].typ!="none":
				outputdata=outputdata+","+x.geraete.device[n].resultform
				currPos=self.visa.getStepPos(x.geraete.getDeviceName(),x.gpib.getAddress())
				head.append("# "+x.geraete.device[n].name +", current Value: "+str(currPos)+", Axes: "+str(x.axes.currentText())+", Outputdata: "+x.geraete.device[n].resultform)
		for x in self.writereadconf.device:
			n=x.geraete.currentItem()
			if x.geraete.device[n].typ!="none":
				outputdata=outputdata+","+x.geraete.device[n].resultform
				if x.mode.currentItem()==1:
					head.append("# "+x.geraete.device[n].name +": "+str(x.beginn.currentText())+", Axes: "+str(x.axes.currentText())+", Outputdata: "+x.geraete.device[n].resultform)
				elif x.mode.currentItem()==2:
					head.append("# "+x.geraete.device[n].name +": from "+str(x.beginn.currentText())+" to "+str(x.ende.currentText())+", Axes: "+str(x.axes.currentText())+", Outputdata: "+x.geraete.device[n].resultform)
				elif x.mode.currentItem()==0:
					head.append("# "+x.geraete.device[n].name +": Axes: "+str(x.axes.currentText())+", Outputdata: "+x.geraete.device[n].resultform)
		
		head.append("# Average over "+str(self.countCombo.currentText())+" measurement points, wait time between 2 readings: "+str(self.waitCombo.currentText()))
		head.append("# Columns: x, y, y2 (as set to axes), then all output data in order of the instruments above, see below")
		head.append("# "+unicode(self.comment.text()))
		head.append("#")
		head.append("# "+outputdata)
		return head
		
		
	#Add x,y,y2 into the first 3 cols of erg
	def extractData(self,x,erg,tmp):
		#first 3 cols of erg are filled with 0, copy values to the front...
		for y in tmp: erg.append(y)
		
		if len(tmp)<2: 
			tmp.append("0") #x
			tmp.append("0") #y

			
		if x.axes.currentItem()==1: erg[0]=tmp[0] #x
		if x.axes.currentItem()==2: erg[1]=tmp[0] #y
		
		if x.axes.currentItem()==3:  #x,y
			erg[0]=tmp[0]
			erg[1]=tmp[1]
				
		if x.axes.currentItem()==4:  #y,x
			erg[1]=tmp[0]
			erg[0]=tmp[1]
		
		if x.axes.currentItem()==5: erg[0]=tmp[1] #-,x
		if x.axes.currentItem()==6: erg[1]=tmp[1] #-,y
		if x.axes.currentItem()==7: erg[2]=tmp[0] #y2
		if x.axes.currentItem()==8: erg[2]=tmp[1] #-,y2
		
	
		#if x.axes.currentItem()==3: erg[2]=tmp[0] #x2
		#if x.axes.currentItem()==4: erg[3]=tmp[0] #y2		
		#if x.axes.currentItem()==7:  #x2,y2
		#	erg[2]=tmp[0]
		#	erg[3]=tmp[1]
		#		
		#if x.axes.currentItem()==8:  #y2,x2
		#	erg[3]=tmp[0]
		#	erg[2]=tmp[1]
		#if x.axes.currentItem()==11: erg[2]=tmp[1] #-,x2
		#if x.axes.currentItem()==12: erg[3]=tmp[1] #-,y2
		
		#print tmp,"extractData: ",erg
		
		return erg
		
	def newMessdaten(self):
		devi=0
		erg=[]
		for y in self.batchwritereadconf.device,self.writereadconf.device:
			for x in y:
				p=x.geraete.current
				if x.geraete.device[p].typ!='none':
					while len(erg)<(devi+1):
						erg.append([])
						#print "apapne"
					tmp=self.visa.getData(x.geraete.getDeviceName(),x.gpib.getAddress())
					#print tmp	
					#print len(erg),devi,len(tmp)
					
					while len(erg[devi])<len(tmp):
						erg[devi].append([0.0,0.0,0.0])
					i=0	
					while i<len(tmp):
						erg[devi][i]=self.extractData(x,erg[devi][i],tmp[i])
						i+=1
					devi+=1
			
		#Search the devicedata with most datalines
		maxn=-1
		i=0
		while i<len(erg):
			if len(erg[i])>maxn: maxn=len(erg[i])
			i+=1
				
		#print erg
		#print maxn
		i=0
		#Aufffuellen
		while i<len(erg):
			#print "i",i
			#print "len(erg)",len(erg)
			
			if len(erg[i])>0: lastdata=erg[i][len(erg[i])-1]
			else: lastdata=[0.0]
			while len(erg[i])<maxn:
				erg[i].append(lastdata)
			i+=1
			
		#print erg
		
		#erg Form is now
		# [ [dev1: [dev1data1],[dev1data2],[...(maxn)] ] [dev2: [dev2data1],[dev2data2],[...] ] [...] ]
		# should become now
		# [ [dev1data1, dev2data1, dev3data1,...] [dev1data2, dev2data2, dev3data2,...][...] ]
		erg2=[]
		#zussammenfuegen
		i=0
		while i<maxn:
			devi=0
			lis=[0,0,0]
			while devi<len(erg): #len(erg)==number of devices
				if erg[devi][i][0]!=0:
					lis[0]=erg[devi][i][0]
				if erg[devi][i][1]!=0:
					lis[1]=erg[devi][i][1]
				if erg[devi][i][2]!=0:
					lis[2]=erg[devi][i][2]
				i2=3 #x,y,y2, dann alle Messdaten
				while i2<len(erg[devi][i]):
					lis.append(erg[devi][i][i2])
					i2+=1
				devi+=1
				
			erg2.append(lis)
			i+=1
			
			
		#print erg2
			
		text=[]
		while len(text)<len(erg2):
			text.append("")
		
		i=0
		while i<len(erg2):
			for x in erg2[i]:
				if text[i]=='':
					text[i]=str(x)
				else: text[i]=text[i]+" "+str(x)
			i+=1
			
		#print text

		self.emit(PYSIGNAL('newMessdaten'),(text,erg2))
		
		#Variablen, die an die Geraete gegeben werden
		i=0
		while i<len(erg2):
			self.plotLastXValue=self.plotXValue
			self.plotLastYValue=self.plotYValue
			self.plotYValue=float(erg2[i][1])
			self.plotXValue=float(erg2[i][0])
			self.plotIntegral=self.plotIntegral+abs(self.plotXValue-self.plotLastXValue)*((self.plotYValue+self.plotLastYValue)/2.0)
			i+=1
		
		self.visa.plotProperties(self.plotLastXValue,self.plotLastYValue,self.plotYValue,self.plotXValue,self.plotIntegral)
		self.writereadconf.nextMesspunkt()


	def setCombo(self,combo,item,allowAdd=True):
		i=0
		found=False
		while i<combo.count():
			if combo.text(i)==item:
				combo.setCurrentItem(i)
				found=True
				return True
			i+=1
				
		if found==False:
			if allowAdd==True:
				combo.setDuplicatesEnabled ( True )
				#print item,"ende"
				combo.insertItem(str(item))
				combo.setCurrentItem(combo.count()-1)
				return True
			else: 
				print "setCombo: not Found"
				return False
					
					
	def new(self):
		n=len(self.batchwritereadconf.device)
		i=0
		while i<n:		
			self.batchwritereadconf.device[i].geraete.setCurrentItem(0)
			self.batchwritereadconf.device[i].geraete.emit(SIGNAL("activated(int)"),(self.batchwritereadconf.device[i].geraete.currentItem(),))
			self.batchwritereadconf.device[i].gpib.setCurrentItem(0)
			#self.batchwritereadconf.device[i].beginn.setCurrentItem(0)
			#self.batchwritereadconf.device[i].ende.setCurrentItem(0)
			self.batchwritereadconf.device[i].steps.setCurrentItem(0)
			self.batchwritereadconf.device[i].mode.setCurrentItem(0)
			self.batchwritereadconf.device[i].axes.setCurrentItem(0)
			i+=1
			
		i=n-1
		while i>0:
			self.batchwritereadconf.device[i].close()
			self.writereadconf.device.pop(i)
			i-=1
			
		n=len(self.writereadconf.device)
		i=0
		while i<n:		
			self.writereadconf.device[i].geraete.setCurrentItem(0)
			self.writereadconf.device[i].geraete.emit(SIGNAL("activated(int)"),(self.writereadconf.device[i].geraete.currentItem(),))
			self.writereadconf.device[i].gpib.setCurrentItem(0)
			#self.writereadconf.device[i].beginn.setCurrentItem(0)
			#self.writereadconf.device[i].ende.setCurrentItem(0)
			self.writereadconf.device[i].steps.setCurrentItem(0)
			self.writereadconf.device[i].mode.setCurrentItem(0)
			self.writereadconf.device[i].axes.setCurrentItem(0)
			i+=1
			
		i=n-1
		while i>0:
			self.writereadconf.device[i].close()
			self.writereadconf.device.pop(i)
			i-=1
			
		#print len(self.writereadconf.device)

		self.countCombo.setCurrentItem(1)
		self.comment.setText("")
					
	def load(self,loadlist):
		#print "load"
		#print loadlist
		self.new()
		for x in loadlist:
			if x[0]=="batchwritereadconf":
				i=int(x[1])
				while len(self.batchwritereadconf.device)<=i:
					print "Adding Devices"
					self.batchwritereadconf.moreclicked()
					
				if x[2]=="device": 
					if self.setCombo(self.batchwritereadconf.device[i].geraete,str(x[3]),False)==True:
						self.batchwritereadconf.device[i].geraete.emit(SIGNAL("activated(int)"),(self.batchwritereadconf.device[i].geraete.currentItem(),))
					else:
						QMessageBox.critical( self, "pyvLab", "ERROR: Instrument not found in devicesconfig.py: "+str(x[3]))
				if x[2]=="gpib": self.setCombo(self.batchwritereadconf.device[i].gpib,str(x[3]))
				if x[2]=="begin": self.setCombo(self.batchwritereadconf.device[i].beginn,str(x[3]))
				if x[2]=="end": self.setCombo(self.batchwritereadconf.device[i].ende,str(x[3]))
				if x[2]=="steps": self.setCombo(self.batchwritereadconf.device[i].steps,str(x[3]))
				if x[2]=="mode": self.setCombo(self.batchwritereadconf.device[i].mode,str(x[3]))
				if x[2]=="axes": self.setCombo(self.batchwritereadconf.device[i].axes,str(x[3]))

			if x[0]=="writereadconf":
				i=int(x[1])
				while len(self.writereadconf.device)<=i:
					print "Adding Devices"
					self.writereadconf.moreclicked()
					
				if x[2]=="device": 
					if self.setCombo(self.writereadconf.device[i].geraete,str(x[3]),False)==True:
						self.writereadconf.device[i].geraete.emit(SIGNAL("activated(int)"),(self.writereadconf.device[i].geraete.currentItem(),))
					else:
						QMessageBox.critical( self, "pyvLab", "ERROR: Instrument not found in devicesconfig.py: "+str(x[3]))

				if x[2]=="gpib": self.setCombo(self.writereadconf.device[i].gpib,str(x[3]))
				if x[2]=="begin": self.setCombo(self.writereadconf.device[i].beginn,str(x[3]))
				if x[2]=="end": self.setCombo(self.writereadconf.device[i].ende,str(x[3]))
				if x[2]=="steps": self.setCombo(self.writereadconf.device[i].steps,str(x[3]))
				if x[2]=="mode": self.setCombo(self.writereadconf.device[i].mode,str(x[3]))
				if x[2]=="axes": self.setCombo(self.writereadconf.device[i].axes,str(x[3]))
				
			if x[0]=="average":
				self.setCombo(self.countCombo,x[1])
				
			if x[0]=="reverseRange":
				self.reverseCheckbox.setChecked(x[1])
				
			if x[0]=="waitTime":
				self.setCombo(self.waitCombo,x[1])
				
			if x[0]=="comment":
				self.comment.setText(str(x[1]))
				
			if x[0]=="repeatTimes":
				self.setCombo(self.repeatCombo,x[1])
		
	def save(self):
		n=len(self.batchwritereadconf.device)
		i=0
		sav=[]
		while i<n:
			sav.append( ("batchwritereadconf",str(i),"device",str(self.batchwritereadconf.device[i].geraete.currentText())))
			sav.append( ("batchwritereadconf",str(i),"begin",str(self.batchwritereadconf.device[i].beginn.currentText())))
			sav.append( ("batchwritereadconf",str(i),"end",str(self.batchwritereadconf.device[i].ende.currentText())))
			sav.append( ("batchwritereadconf",str(i),"steps",str(self.batchwritereadconf.device[i].steps.currentText())))
			sav.append( ("batchwritereadconf",str(i),"mode",str(self.batchwritereadconf.device[i].mode.currentText())))
			sav.append( ("batchwritereadconf",str(i),"gpib",str(self.batchwritereadconf.device[i].gpib.currentText())))
			sav.append( ("batchwritereadconf",str(i),"axes",str(self.batchwritereadconf.device[i].axes.currentText())))
			i+=1

		n=len(self.writereadconf.device)
		i=0
		while i<n:
			sav.append( ("writereadconf",str(i),"device",str(self.writereadconf.device[i].geraete.currentText())))
			sav.append( ("writereadconf",str(i),"begin",str(self.writereadconf.device[i].beginn.currentText())))
			sav.append( ("writereadconf",str(i),"end",str(self.writereadconf.device[i].ende.currentText())))
			sav.append( ("writereadconf",str(i),"steps",str(self.writereadconf.device[i].steps.currentText())))
			sav.append( ("writereadconf",str(i),"mode",str(self.writereadconf.device[i].mode.currentText())))
			sav.append( ("writereadconf",str(i),"gpib",str(self.writereadconf.device[i].gpib.currentText())))
			sav.append( ("writereadconf",str(i),"axes",str(self.writereadconf.device[i].axes.currentText())))
			i+=1
			
		sav.append( ("average",str(self.countCombo.currentText())))
		sav.append( ("waitTime",str(self.waitCombo.currentText())))
		sav.append( ("reverseRange",self.reverseCheckbox.isChecked()))
		sav.append( ("comment",unicode(self.comment.text())))
		sav.append( ("repeatTimes",unicode(self.repeatCombo.currentText())))
		return sav
			
			
			
